/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controls;

import com.aptech.bluepumpkin.Users;
import com.aptech.bluepumpkin.beans.UsersFacade;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utils.Constants;
import utils.Uility;

/**
 *
 * @author Chien
 */
@ManagedBean
@SessionScoped
public class UserControl implements Serializable{

    @EJB
    private UsersFacade usersFacade;
    /**
     * Users is pricipal, authenticated user DO NOT USE it, unless mofdify Users
     * profile. user user is set only logon.
     */
    private Users user;
    /**
     * selectedtuser is used as tempory user. Ex: select an user and show it's
     * profile
     */
    private Users selectedtuser;
    /**
     * newUser: is use to add new user, can not use selectedUser, because of
     * changing selected Users's profile
     */
    private Users newUser = new Users();
    boolean validEmail = false;
    private String email = "";
    private String avatar = "";
    /**
     * Used by newUser
     */
    private String newAvatar = "";
    private String oldPassword ="";

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }
    

    public String getNewAvatar() {
        return newAvatar;
    }

    public void setNewAvatar(String newAvatar) {
        this.newAvatar = newAvatar;
    }

    public Date minDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, -60);
        return cal.getTime();
    }

    public Date maxDOB() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, -18);
        return cal.getTime();
    }

    public Date currentDate() {
        return new Date();
    }

    public void resetUser() {
        newUser = new Users();

    }
    boolean passwordMatch =false;
    private String newPassword ="";

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }
    
    public void checkPassword(){
        String oldpw = Uility.getMD5(oldPassword);
        if(oldpw.equals(user.getPassword())){
            passwordMatch =true;
        }else{
            passwordMatch =false;
        }
    }
    public boolean getMatchPassword(){
        return  !passwordMatch;
    }
    public void changePassword(){
        if(passwordMatch){
            user.setPassword(Uility.getMD5(newPassword));
            update(user);
            logout();
        }
    }
/**
 * Update User that logon web site
 */
    public void editLogonProfile() {
        update(user);
         redirectToListUserPage();
    }

    public void editUserPorfile() {
        update(selectedtuser);
         redirectToListUserPage();

    }

    public void update(Users users) {
        try {

            usersFacade.edit(users);

           
        } catch (Exception ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Upload image, ONLY USED with Edit login Users's Profile (principal)
     *
     * @param event FileUploadEvent
     */
    public void handleFileUploadEditProfile(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    avatar = Constants.DATABASE_IMAGE_PATH + time + ext;
                    if (null != user) {
                        user.setAvatar(avatar);
                    }
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + avatar);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }
    }

    /**
     * Upload image, ONLY USED with Edit login Users's Profile (principal)
     *
     * @param event FileUploadEvent
     */
    public void handleFileUploadAddUser(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg

                    newAvatar = Constants.DATABASE_IMAGE_PATH + time + ext;
                    if (null != newUser) {
                        newUser.setAvatar(newAvatar);
                    }
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + avatar);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isValidEmail() {
        return validEmail;
    }

    public void setValidEmail(boolean validEmail) {
        this.validEmail = validEmail;
    }

    /**
     * Creates a new instance of UserControl
     */
    public UserControl() {
        user = new Users();
        selectedtuser = new Users();
        newUser = new Users();


    }

    public void gotoLoginpage() {
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/loginPage.xhtml";
        redicrectToPage(context, path);
    }

    public void checkEmail(ActionEvent actionEvent) {

        Users checkUs = usersFacade.checkEmail(getEmail());
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage("", new FacesMessage("Invalid email."));
        String path = "/faces/userWeb/loginPage.xhtml";
        if (null != checkUs) {
            redicrectToPage(context, path);
        }
    }

    public void forgotPassword() {
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/forgotPassword.xhtml";
        redicrectToPage(context, path);
    }

    /**
     * logout
     */
    public void logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("user", null);
        this.user = new Users();
        try {
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/loginPage.xhtml");
        } catch (Exception e) {
        }

    }

    public void resetPasswordAndSendMail(Users user) {
       
      selectedtuser =user;
//         FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Password is reseted","Password is reseted"));
        if (null != selectedtuser) {
            if (null != selectedtuser.getEmail() && !selectedtuser.getEmail().isEmpty()) {
                try {
                    System.out.println("-------start sending email----------------");
                   
                    String newPasswordStr = Uility.createRandomPassword(8);
                    String subject ="From: www.BluePumpkin.com, Content: Reset your password";
                    Uility.sendMail(selectedtuser.getEmail(),subject ,newPasswordStr);
                    
                    selectedtuser.setPassword(Uility.getMD5(newPasswordStr));
                    update(selectedtuser);
                    
                   System.out.println("-------end sending email----------------");
                } catch (MessagingException ex) {
                    Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }else{
                System.out.println("-------Email is empty--------------"+selectedtuser.getEmail());
            }
        }else{
            System.out.println("---------Select User is NUll");
        }
         FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Password is reseted","Password is reseted"));
    }

    private void redicrectToPage(FacesContext context, String path) {
        if (null == context) {
            return;
        }
        try {
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + path);
        } catch (Exception e) {
        }
    }

    /**
     * modified by Trong
     */
    public void checkLogin() {
        // MD5 password
        user.setPassword(Uility.getMD5(user.getPassword()));
        this.user = usersFacade.checkLogin(user);
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/loginPage.xhtml";
//        user not found
        if (null == this.user) {
            redicrectToPage(context, path);
        }

        boolean isActive = this.user.getActive();
        // if not active
        if (!isActive) {
            redicrectToPage(context, path);
        }
        boolean role = user.getIsAdmin();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("user", user);
        if (role) {
            try {
                context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/admin/event/adminHomePage.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/home.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public List<Users> getAllUser() {
        List<Users> findAll = usersFacade.findAll();
        findAll.remove(user);
        return findAll;
    }

    public void delete(Users user) {

        FacesContext context = FacesContext.getCurrentInstance();
        try {
            usersFacade.remove(user);

            redirectToListUserPage();


        } catch (Exception ex) {

            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "User is used, You can not delete this user", ""));
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void redirectToAddUserPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/addUser.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }

    public void redirectToListUserPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/userPage.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }

    public void redirectToEditUserPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/editUser.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }

    public void redirectToUserDetailPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/userDetail.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }
    public void redirectToChangePasswordPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/changePassword.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }
  
    /**
     * Edit user that logon web site
     */
    public void redirectToLogonUserPage() {

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/user/editUserProfile.xhtml";
        utils.Uility.redirectPage(context, null, path);
    }

    public void insert() {
        try {
            boolean findUserByUserName = usersFacade.findUserByUserName(newUser.getUsername());
            // username is used
            if (findUserByUserName) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage( "Username already used. INSERT FAIL"));
                return;
            }
            // MD5 password
            newUser.setPassword(Uility.getMD5(newUser.getPassword()));
            usersFacade.create(newUser);
            // create new Users for future creation, MUST HAVE
            newUser = new Users();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage( "Insert Success"));

            redirectToListUserPage();
        } catch (Exception ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public SelectItem[] sexoption() {
        SelectItem[] sexop = new SelectItem[3];
        sexop[0] = new SelectItem("");
        sexop[1] = new SelectItem("Male");
        sexop[2] = new SelectItem("Female");
        return sexop;
    }

    public SelectItem[] createFilterOptions() {
        SelectItem[] options = new SelectItem[8];
        options[0] = new SelectItem("");
        options[1] = new SelectItem("Manager");
        options[2] = new SelectItem("Maketing");
        options[3] = new SelectItem("Sales");
        options[4] = new SelectItem("IT");
        options[5] = new SelectItem("Accounting");
        options[6] = new SelectItem("Protection");
        options[7] = new SelectItem("Other");
        return options;
    }

    public String convertSex(Users user) {
        if (null != user) {
            if (null != user.getGenger() && user.getGenger().booleanValue()) {
                return "Male";

            } else {
                return "Female";
            }
        }
        return "";
    }

    public Users getNewUser() {
        return newUser;
    }

    public void setNewUser(Users newUser) {
        this.newUser = newUser;
    }

    public Users getSelectedtuser() {
        return selectedtuser;
    }

    public void setSelectedtuser(Users selectedtuser) {
        this.selectedtuser = selectedtuser;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }
}
